<!DOCTYPE html>
<html lang="zh-CN" xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>花龙腾航 - 我的机票</title>
    <script src="https://cdn.tailwindcss.com"></script>
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css">
    <style>
        @import url('https://fonts.googleapis.com/css2?family=Noto+Sans+SC:wght@400;500;700&display=swap');

        body {
            font-family: 'Noto Sans SC', sans-serif;
            background-color: #f8fafc;
        }

        .logo-text {
            background: linear-gradient(135deg, #3b82f6, #8b5cf6);
            -webkit-background-clip: text;
            background-clip: text;
            color: transparent;
            font-weight: 700;
        }

        .ticket-card {
            transition: all 0.3s ease;
            box-shadow: 0 1px 3px rgba(0, 0, 0, 0.05);
            border-radius: 12px;
            overflow: hidden;
        }

        .ticket-card:hover {
            transform: translateY(-2px);
            box-shadow: 0 10px 25px -5px rgba(0, 0, 0, 0.1);
        }

        .status-badge {
            padding: 0.25rem 0.75rem;
            border-radius: 9999px;
            font-size: 0.75rem;
            font-weight: 600;
        }

        .tab-active {
            position: relative;
            color: #3b82f6;
            font-weight: 600;
        }

        .tab-active:after {
            content: "";
            position: absolute;
            bottom: -1px;
            left: 0;
            width: 100%;
            height: 3px;
            background: #3b82f6;
            border-radius: 3px 3px 0 0;
        }

        .airplane-icon {
            transform: rotate(90deg);
            color: #3b82f6;
        }

        .highlight {
            background-color: #FEF3C7;
            transition: background-color 0.3s;
        }

        .fade-in {
            animation: fadeIn 0.3s ease-in-out;
        }

        @keyframes fadeIn {
            from { opacity: 0; transform: translateY(10px); }
            to { opacity: 1; transform: translateY(0); }
        }

        .ticket-detail {
            max-height: 0;
            overflow: hidden;
            transition: max-height 0.3s ease-out;
        }

        .ticket-detail.open {
            max-height: 500px;
        }

        .progress-bar {
            height: 6px;
            border-radius: 3px;
            background-color: #e5e7eb;
        }

        .progress-fill {
            height: 100%;
            border-radius: 3px;
            background: linear-gradient(90deg, #3b82f6, #8b5cf6);
            transition: width 0.3s ease;
        }

        .date-picker {
            position: relative;
        }

        .date-picker input {
            padding-right: 2.5rem;
        }

        .date-picker i {
            position: absolute;
            right: 1rem;
            top: 50%;
            transform: translateY(-50%);
            pointer-events: none;
            color: #6b7280;
        }

        .search-box {
            position: relative;
        }

        .search-box i {
            position: absolute;
            left: 1rem;
            top: 50%;
            transform: translateY(-50%);
            color: #9ca3af;
        }

        .search-box input {
            padding-left: 2.5rem;
        }

        .user-avatar {
            background: linear-gradient(135deg, #3b82f6, #8b5cf6);
        }
        .dropdown-menu {
            display: none;
            position: absolute;
            right: 0;
            top: 100%;
            background-color: white;
            border-radius: 0.5rem;
            box-shadow: 0 4px 6px -1px rgba(0, 0, 0, 0.1), 0 2px 4px -1px rgba(0, 0, 0, 0.06);
            min-width: 200px;
            z-index: 10;
        }

        .dropdown-menu.open {
            display: block;
        }

        .dropdown-item {
            padding: 0.5rem 1rem;
            cursor: pointer;
            transition: background-color 0.2s;
        }

        .dropdown-item:hover {
            background-color: #f3f4f6;
        }

        .ticket-header {
            background: linear-gradient(135deg, #3b82f6, #8b5cf6);
            color: white;
            padding: 1rem;
        }

        .boarding-pass {
            border: 2px dashed #e5e7eb;
            border-radius: 8px;
            padding: 1rem;
            position: relative;
        }

        .boarding-pass:before {
            content: "";
            position: absolute;
            top: 50%;
            left: 0;
            right: 0;
            height: 2px;
            background: repeating-linear-gradient(to right, #e5e7eb, #e5e7eb 10px, transparent 10px, transparent 20px);
        }

        .seat-number {
            background: #3b82f6;
            color: white;
            border-radius: 4px;
            padding: 0.25rem 0.5rem;
            font-weight: bold;
        }

        .qr-code {
            width: 100px;
            height: 100px;
            background: #f3f4f6;
            display: flex;
            align-items: center;
            justify-content: center;
            border-radius: 8px;
        }
    </style>
</head>
<body>
<!-- Header -->
<header class="bg-white shadow-sm sticky top-0 z-10">
    <div class="container mx-auto px-4 py-4 flex justify-between items-center">
        <div class="flex items-center space-x-2">
            <i class="fas fa-plane text-3xl text-blue-500"></i>
            <h1 class="text-2xl font-bold logo-text">花龙腾航</h1>
        </div>
        <nav class="hidden md:flex space-x-6">
            <a href="user_index" class="text-gray-600 hover:text-blue-500">首页</a>
            <a href="user_flight_search" class="text-gray-600 hover:text-blue-500">航班查询</a>
            <a href="user_order" class="text-gray-600 hover:text-blue-500">我的订单</a>
            <a href="#" class="text-blue-500 font-medium">我的机票</a>
            <a href="user_member_center" class="text-gray-600 hover:text-blue-500">会员中心</a>
        </nav>
        <div class="flex items-center space-x-4">
            <div class="flex items-center space-x-2 cursor-pointer group relative" id="user-menu">
                <div class="w-8 h-8 rounded-full user-avatar overflow-hidden">
                    <img th:if="${imageExists}" th:src="'static/images/'+${user.getU_id()}+'.jpg?version=' + ${#dates.createNow().time}" alt="用户头像" class="w-full h-full object-cover">
                    <img th:if="${!imageExists} and ${user.getSex()} == '女'" src="https://randomuser.me/api/portraits/women/44.jpg" alt="用户头像" class="w-full h-full object-cover">
                    <img th:if="${!imageExists} and ${user.getSex()} == '男'" src="https://randomuser.me/api/portraits/men/71.jpg" alt="用户头像" class="w-full h-full object-cover">
                </div>
                <span class="hidden md:inline text-gray-700 group-hover:text-blue-500" th:text="${user.getU_name()}">张先生</span>
                <div class="dropdown-menu" id="dropdown-menu">
                    <div class="dropdown-item" onclick="location.href='user_profile'">
                        <i class="fas fa-user-cog mr-2"></i> 个人主页
                    </div>
                    <div class="dropdown-item" onclick="location.href='user_account_manage'">
                        <i class="fas fa-cog mr-2"></i> 账号管理
                    </div>
                    <div class="border-t border-gray-200 my-1"></div>
                    <div class="dropdown-item text-red-500" onclick="location.href='user_logout'">
                        <i class="fas fa-sign-out-alt mr-2"></i> 退出登录
                    </div>
                </div>
            </div>
        </div>
    </div>
</header>

<!-- Main Content -->
<main class="container mx-auto px-4 py-8">
    <div class="flex flex-col md:flex-row gap-8">
        <!-- Sidebar -->
        <aside class="w-full md:w-64 bg-white rounded-xl shadow-sm p-6 h-fit sticky top-24">
            <div class="flex items-center space-x-3 mb-6">
                <div class="h-12 w-12 rounded-full user-avatar flex items-center justify-center text-white text-xl overflow-hidden">
                    <img th:if="${imageExists}" th:src="'static/images/'+${user.getU_id()}+'.jpg?version=' + ${#dates.createNow().time}" alt="用户头像" class="w-full h-full object-cover">
                    <img th:if="${!imageExists} and ${user.getSex()} == '女'" src="https://randomuser.me/api/portraits/women/44.jpg" alt="用户头像" class="w-full h-full object-cover">
                    <img th:if="${!imageExists} and ${user.getSex()} == '男'" src="https://randomuser.me/api/portraits/men/71.jpg" alt="用户头像" class="w-full h-full object-cover">
                </div>
                <div>
                    <h3 class="font-bold text-gray-800" th:text="${user.getU_name()}">张先生</h3>
                    <p class="text-xs text-gray-500" th:text="${user.getGrade()}">黄金会员</p>
                </div>
            </div>

            <nav class="space-y-1">
                <a href="user_profile" class="block px-4 py-2 rounded-lg text-gray-700 hover:bg-blue-50 hover:text-blue-600 transition">
                    <i class="fas fa-user mr-3 text-gray-400"></i> 个人资料
                </a>
                <a href="user_order" class="block px-4 py-2 rounded-lg text-gray-700 hover:bg-blue-50 hover:text-blue-600 transition">
                    <i class="fas fa-ticket mr-3 text-gray-400"></i> 我的订单
                </a>
                <a href="user_ticket" class="block px-4 py-2 rounded-lg bg-blue-50 text-blue-600 font-medium transition">
                    <i class="fas fa-ticket-alt mr-3 text-blue-500"></i> 我的机票
                </a>
                <a href="user_member_center" class="block px-4 py-2 rounded-lg text-gray-700 hover:bg-blue-50 hover:text-blue-600 transition">
                    <i class="fas fa-crown mr-3 text-gray-400"></i> 会员权益
                </a>
                <a href="user_account_manage" class="block px-4 py-2 rounded-lg text-gray-700 hover:bg-blue-50 hover:text-blue-600 transition">
                    <i class="fas fa-cog mr-3 text-gray-400"></i> 账户设置
                </a>
            </nav>
        </aside>

        <!-- Ticket List -->
        <div class="flex-1">
            <div class="bg-white rounded-xl shadow-sm overflow-hidden fade-in">
                <div class="p-6 border-b border-gray-100">
                    <h2 class="text-xl font-bold text-gray-800 mb-2">我的机票</h2>
                    <p class="text-sm text-gray-500">查看和管理您的所有机票</p>
                    <p th:if="${ticket_operation_failure}" style="color: red">操作失败，请重新再试！</p>
                </div>
                <!-- Tabs -->
                <div class="border-b border-gray-200 px-6">
                    <div class="flex space-x-8 overflow-x-auto">
                        <button onclick="filterTickets('all')" class="pb-3 px-1 tab-active" id="tab-all">
                            全部机票 <span id="all-count" class="ml-1 text-xs font-normal bg-blue-100 text-blue-600 px-2 py-0.5 rounded-full" th:text="${allTicketCounts}">5</span>
                        </button>
                        <button onclick="filterTickets('upcoming')" class="pb-3 px-1 text-gray-500 hover:text-blue-500" id="tab-upcoming">
                            即将起飞 <span id="upcoming-count" class="ml-1 text-xs font-normal bg-gray-100 text-gray-600 px-2 py-0.5 rounded-full" th:text="${upcomingTicketCounts}">3</span>
                        </button>
                        <button onclick="filterTickets('scheduled')" class="pb-3 px-1 text-gray-500 hover:text-blue-500" id="tab-scheduled">
                            计划中 <span id="scheduled-count" class="ml-1 text-xs font-normal bg-gray-100 text-gray-600 px-2 py-0.5 rounded-full" th:text="${plannedTicketCounts}">1</span>
                        </button>
                        <button onclick="filterTickets('completed')" class="pb-3 px-1 text-gray-500 hover:text-blue-500" id="tab-completed">
                            已完成 <span id="completed-count" class="ml-1 text-xs font-normal bg-gray-100 text-gray-600 px-2 py-0.5 rounded-full" th:text="${completedTicketCounts}">1</span>
                        </button>
                        <button onclick="filterTickets('cancelled')" class="pb-3 px-1 text-gray-500 hover:text-blue-500" id="tab-cancelled">
                            已取消 <span id="cancelled-count" class="ml-1 text-xs font-normal bg-gray-100 text-gray-600 px-2 py-0.5 rounded-full" th:text="${cancelledTicketCounts}">1</span>
                        </button>
                        <button onclick="filterTickets('delay')" class="pb-3 px-1 text-gray-500 hover:text-blue-500" id="tab-delay">
                            已延误 <span id="delay-count" class="ml-1 text-xs font-normal bg-gray-100 text-gray-600 px-2 py-0.5 rounded-full" th:text="${delayTicketCounts}">1</span>
                        </button>
                        <!--button onclick="filterTickets('pending_payment')" class="pb-3 px-1 text-gray-500 hover:text-blue-500" id="tab-pending_payment">
                            待支付 <span id="pending-payment-count" class="ml-1 text-xs font-normal bg-gray-100 text-gray-600 px-2 py-0.5 rounded-full" th:text="${unpaidTicketCounts}">1</span>
                        </button>
                        <button onclick="filterTickets('pending_refund')" class="pb-3 px-1 text-gray-500 hover:text-blue-500" id="tab-pending_refund">
                            待退款 <span id="pending-refund-count" class="ml-1 text-xs font-normal bg-gray-100 text-gray-600 px-2 py-0.5 rounded-full" th:text="${refundTicketCounts}">1</span>
                        </button-->
                    </div>
                </div>

                <!-- Search and Filter -->
                <div class="p-6 border-b border-gray-100">
                    <div class="flex flex-col md:flex-row justify-between items-start md:items-center gap-4">
                        <div class="flex-1 flex flex-col md:flex-row gap-4">
                            <div class="search-box flex-1">
                                <i class="fas fa-search"></i>
                                <input type="text" id="searchInput" placeholder="搜索机票号、航班号或目的地..." class="w-full pl-10 pr-4 py-2 border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-500 focus:border-blue-500">
                            </div>

                            <div class="date-picker">
                                <input type="date" id="dateFilter" class="border border-gray-300 rounded-lg px-4 py-2 focus:ring-2 focus:ring-blue-500 focus:border-blue-500 bg-gray-50">
                                <i class="fas fa-calendar-alt"></i>
                            </div>
                        </div>

                        <div class="flex space-x-2 w-full md:w-auto">
                            <select id="statusFilter" class="border border-gray-300 rounded-lg px-3 py-2 focus:outline-none focus:ring-2 focus:ring-blue-500 focus:border-blue-500 bg-gray-50">
                                <option value="">所有状态</option>
                                <option value="upcoming">即将起飞</option>
                                <option value="scheduled">计划中</option>
                                <option value="completed">已完成</option>
                                <option value="cancelled">已取消</option>
                                <option value="delay">已延误</option>
                                <!--option value="pending_payment">待支付</option>
                                <option value="pending_refund">待退款</option-->
                            </select>
                            <button class="bg-blue-500 hover:bg-blue-600 text-white px-4 py-2 rounded-lg flex items-center transition" onclick="applyFilters()">
                                <i class="fas fa-filter mr-2"></i> 筛选
                            </button>
                        </div>
                    </div>
                </div>

                <!-- Ticket List -->
                <div class="divide-y divide-gray-100" id="ticket-list">
                    <div class="ticket-card bg-white transition duration-300" th:each="ticket : ${tickets}">
                        <div class="ticket-header flex justify-between items-center">
                            <div>
                                <div class="text-sm" th:text="'航班号: ' + ${ticket.getFlight_id()}+'&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;机票号: '+${ticket.getTicket_id()}">机票号: HL20231115-001</div>
                                <div class="text-xs opacity-80" th:text="'出发日期：'+${ticket.getDate()}+'  '+${ticket.getDeparture_day()}+'&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;到达日期：'+${ticket.getArrival_date()}+'  '+${ticket.getArrival_day()}">2023年11月15日</div>
                            </div>
                            <span class="status-badge" th:classappend="${ticket.getStatusText() == '即将起飞'} ? 'bg-blue-100 text-blue-800' :
                                                                      (${ticket.getStatusText() == '计划中'} ? 'bg-purple-100 text-purple-800' :
                                                                      (${ticket.getStatusText() == '已完成'} ? 'bg-green-100 text-green-800' :
                                                                      (${ticket.getStatusText() == '已取消'} ? 'bg-red-100 text-red-800' :
                                                                      (${ticket.getStatusText() == '已延误'} ? 'bg-yellow-100 text-yellow-800' :
                                                                      (${ticket.getStatusText() == '待退款'} ? 'bg-orange-100 text-orange-800' :
                                                                      'bg-yellow-100 text-yellow-800')))))" th:text="${ticket.getStatusText()}">已出票
                            </span>
                        </div>

                        <div class="p-6">
                            <div class="flex justify-between items-start mb-4">
                                <div class="flex items-center space-x-4">
                                    <div class="text-center">
                                        <div class="text-xl font-bold" th:text="${ticket.getDeparture_city()}">上海</div>
                                        <div class="text-xs text-gray-500" th:text="${ticket.getDeparture_airport()}">(SHA)</div>
                                    </div>
                                    <div class="flex flex-col items-center">
                                        <div class="text-sm text-gray-500" th:text="${ticket.getDeparture_time()}">08:30</div>
                                        <div class="my-1 airplane-icon">
                                            <i class="fas fa-plane"></i>
                                        </div>
                                        <div class="text-sm text-gray-500" th:text="${ticket.getArrival_time()}">10:45</div>
                                    </div>
                                    <div class="text-center">
                                        <div class="text-xl font-bold" th:text="${ticket.getArrival_city()}">上海</div>
                                        <div class="text-xs text-gray-500" th:text="${ticket.getArrival_airport()}">(SHA)</div>
                                    </div>
                                </div>
                                <div class="text-right">
                                    <div class="text-2xl font-bold text-blue-600" th:text="'¥' + ${ticket.getPrice()}">¥1280</div>
                                    <div class="text-sm text-gray-500" th:text="${ticket.getSeat_type()}">经济舱</div>
                                </div>
                            </div>

                            <!--div class="boarding-pass p-4 flex justify-between items-center" th:if="${ticket.getStatusText() != '待支付'}"-->
                            <div class="boarding-pass p-4 flex justify-between items-center">
                                <div>
                                    <div class="font-medium" th:text="${ticket.getPassenger_name()}">张伟</div>
                                    <div class="text-sm text-gray-600 mt-1">乘客</div>
                                    <div class="flex items-center mt-2">
                                        <span class="seat-number mr-2" th:text="${ticket.getSeat()}" th:if="${ticket.getSeat()}">12A</span>
                                        <span class="seat-number mr-2" th:unless="${ticket.getSeat()}">暂无</span>
                                        <span class="text-sm" th:text="${ticket.getGate() != null} ? '登机口: ' + ${ticket.getGate()} : '登机口: 待定'">登机口: 待定</span>
                                    </div>
                                </div>
                                <div class="qr-code">
                                    <i class="fas fa-qrcode text-3xl text-gray-400" th:if="${ticket.getStatusText() != '已完成'}"></i>
                                    <i class="fas fa-check-circle text-3xl text-green-500" th:if="${ticket.getStatusText() == '已完成'}"></i>
                                </div>
                            </div>

                            <div class="mt-4 flex justify-between items-center border-t border-gray-100 pt-4">
                                <div class="text-xs" th:classappend="${ticket.getStatusText() == '即将起飞'} ? 'text-blue-600' :
                                                                     (${ticket.getStatusText() == '计划中'} ? 'text-purple-600' :
                                                                     (${ticket.getStatusText() == '已完成'} ? 'text-green-600' :
                                                                     (${ticket.getStatusText() == '已取消'} ? 'text-red-600' :
                                                                     (${ticket.getStatusText() == '已延误'} ? 'text-orange-600' :
                                                                     'text-yellow-600'))))">
                                    <i class="fas fa-check-circle mr-1" th:if="${ticket.getStatusText() == '即将起飞'}">即将起飞</i>
                                    <i class="fas fa-check-circle mr-1" th:if="${ticket.getStatusText() == '计划中'}">计划中</i>
                                    <i class="fas fa-check-circle mr-1" th:if="${ticket.getStatusText() == '已完成'}">已完成</i>
                                    <i class="fas fa-times-circle mr-1" th:if="${ticket.getStatusText() == '已取消'}">已取消</i>
                                    <i class="fas fa-exclamation-circle mr-1" th:if="${ticket.getStatusText() == '已延误'}">待支付</i>
                                </div>
                                <form id="ticketForm" method="post" action="user_ticket_operation">
                                    <div class="flex space-x-2">
                                        <!-- 隐藏字段用于传递 ticketId & flightId -->
                                        <input type="hidden" name="ticketId" id="ticketIdInput">
                                        <input type="hidden" name="flightId" id="flightIdInput">
                                        <input type="hidden" name="actionType" id="actionTypeInput">
                                        <!-- 操作按钮 -->
                                        <button class="px-4 py-2 bg-green-500 hover:bg-green-600 text-white rounded-lg text-sm transition"
                                                th:if="${ticket.getStatusText() == '计划中'}"
                                                th:attr="data-ticket-id=${ticket.getId()}, data-flight-id=${ticket.getFlightNo()}"
                                                onclick="handleTicketAction(this, 'reschedule')">
                                            改签
                                        </button>
                                        <button class="px-4 py-2 bg-red-500 hover:bg-red-600 text-white rounded-lg text-sm transition"
                                                th:if="${ticket.getStatusText() == '计划中'}"
                                                th:attr="data-ticket-id=${ticket.getId()}, data-flight-id=${ticket.getFlightNo()}"
                                                onclick="handleTicketAction(this, 'refund')">
                                            退票
                                        </button>
                                        <button class="px-4 py-2 bg-red-500 hover:bg-red-600 text-white rounded-lg text-sm transition"
                                                th:if="${ticket.getStatusText() == '即将起飞'}"
                                                th:attr="data-ticket-id=${ticket.getId()}, data-flight-id=${ticket.getFlightNo()}"
                                                onclick="handleTicketAction(this, 'refund')">
                                            退票
                                        </button>
                                        <button class="px-4 py-2 bg-red-500 hover:bg-red-600 text-white rounded-lg text-sm transition"
                                                th:if="${ticket.getStatusText() == '已延误'}"
                                                th:attr="data-ticket-id=${ticket.getId()}, data-flight-id=${ticket.getFlightNo()}"
                                                onclick="handleTicketAction(this, 'refund')">
                                            退票
                                        </button>
                                        <!--button type="button"
                                                class="px-4 py-2 bg-red-500 hover:bg-red-600 text-white rounded-lg text-sm transition"
                                                th:if="${ticket.getStatusText() == '待支付'}"
                                                th:attr="data-ticket-id=${ticket.getId()}, data-flight-id=${ticket.getFlightNo()}"
                                                onclick="handleTicketAction(this, 'cancel')">
                                            取消机票
                                        </button>
                                        <button class="px-4 py-2 bg-blue-500 hover:bg-blue-600 text-white rounded-lg text-sm transition"
                                                th:if="${ticket.getStatusText() == '待支付'}"
                                                th:attr="data-ticket-id=${ticket.getId()}, data-flight-id=${ticket.getFlightNo()}"
                                                onclick="handleTicketAction(this, 'pay')">
                                            立即支付
                                        </button-->
                                        <button class="px-4 py-2 border border-gray-300 hover:bg-gray-50 rounded-lg text-sm transition"
                                                th:if="${ticket.getStatusText() == '已完成'}"
                                                th:attr="data-ticket-id=${ticket.getId()}, data-flight-id=${ticket.getFlightNo()}"
                                                onclick="handleTicketAction(this, 'rebook')">
                                            再次预订
                                        </button>
                                        <button type="button"
                                                class="px-4 py-2 border border-gray-300 hover:bg-gray-50 rounded-lg text-sm transition flex items-center"
                                                onclick="toggleTicketDetail(this)">
                                            <span>详情</span>
                                            <i class="fas fa-chevron-down ml-1 text-xs"></i>
                                        </button>
                                    </div>
                                </form>
                            </div>
                            <div class="ticket-detail mt-2">
                                <div class="border-t border-gray-100 pt-4">
                                    <h4 class="font-medium text-gray-700 mb-3"></h4>
                                    <div class="grid grid-cols-1 md:grid-cols-3 gap-4">
                                        <div class="bg-gray-50 p-3 rounded-lg">
                                            <div class="font-medium">乘客信息</div>
                                            <div class="flex justify-between">
                                                <span class="font-sm" th:text="${user.getU_name()}">张伟</span>
                                                <span class="text-sm text-gray-500" th:text="${ticket.getPassenger_type()}">成人</span>
                                            </div>
                                            <div class="mt-2 text-sm text-gray-600">
                                                <div class="flex justify-between">
                                                    <span>座位:</span>
                                                    <span class="font-medium" th:text="${ticket.getSeat() != null} ? ${ticket.getSeat()} : '待值机'">12A</span>
                                                </div>
                                                <div class="flex justify-between mt-1">
                                                    <span>餐食:</span>
                                                    <span class="font-medium" th:text="${ticket.getMeal_money()}+' - '+${ticket.getMeal()}">标准餐</span>
                                                </div>
                                            </div>
                                        </div>
                                        <!-- 行李 -->
                                        <div class="bg-gray-50 p-3 rounded-lg">
                                            <div class="font-medium">行李信息</div>
                                            <div class="mt-2 text-sm text-gray-600">
                                                <div class="flex justify-between">
                                                    <span>行李额度:</span>
                                                    <span class="font-medium" th:text="'1件，每件不超过'+${ticket.getBaggage_limit()}">2件，每件不超过23kg</span>
                                                </div>
                                            </div>
                                        </div>
                                        <!-- 飞机 -->
                                        <div class="bg-gray-50 p-3 rounded-lg">
                                            <div class="font-medium">飞机信息</div>
                                            <div class="mt-2 text-sm text-gray-600">
                                                <div class="flex justify-between">
                                                    <span>航司:</span>
                                                    <span class="font-medium" th:text="${ticket.getP_airline()}">南方航空公司</span>
                                                </div>
                                                <div class="flex justify-between mt-1">
                                                    <span>飞机型号:</span>
                                                    <span class="font-medium" th:text="${ticket.getP_model()}">C919</span>
                                                </div>
                                                <div class="flex justify-between mt-1">
                                                    <span>机龄:</span>
                                                    <span class="font-medium" th:text="${ticket.getPlane_age()}">18</span>
                                                </div>
                                                <div class="flex justify-between mt-1">
                                                    <span>WiFi:</span>
                                                    <span class="font-medium" th:text="${ticket.getWiFi} == 'no' ? '暂无提供' : (${ticket.getWiFi} == 'true' ? '免费提供' : '付费使用')">免费提供</span>
                                                </div>
                                            </div>
                                        </div>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>



                    <!-- Empty State -->
                    <div id="empty-state" class="hidden p-12 text-center">
                        <i class="fas fa-ticket-alt text-4xl text-gray-300 mb-4"></i>
                        <h3 class="text-lg font-medium text-gray-700">没有找到符合条件的机票</h3>
                        <p class="text-gray-500 mt-1">请尝试修改筛选条件或<a href="#" class="text-blue-500 hover:underline">预订新航班</a></p>
                    </div>

                    <!-- Pagination -->
                    <div class="p-6 border-t border-gray-200 flex flex-col md:flex-row justify-between items-center gap-4">
                        <div class="text-sm text-gray-600">
                            显示 <span id="startItem" class="font-medium">1</span> 到 <span id="endItem" class="font-medium">3</span> 条，共 <span id="totalItems" class="font-medium">3</span> 条机票
                        </div>
                        <div class="flex items-center space-x-4">
                            <div class="flex items-center space-x-2">
                                <button id="prevPage" class="px-3 py-1.5 border border-gray-300 rounded-lg bg-white text-gray-700 hover:bg-gray-50 disabled:opacity-50 disabled:cursor-not-allowed flex items-center transition" disabled>
                                    <i class="fas fa-chevron-left mr-1 text-xs"></i>
                                    <span>上一页</span>
                                </button>
                                <div id="pageNumbers" class="flex space-x-1">
                                    <button class="px-3 py-1 rounded-lg text-sm font-medium bg-blue-600 text-white">1</button>
                                </div>
                                <button id="nextPage" class="px-3 py-1.5 border border-gray-300 rounded-lg bg-white text-gray-700 hover:bg-gray-50 flex items-center transition" disabled>
                                    <span>下一页</span>
                                    <i class="fas fa-chevron-right ml-1 text-xs"></i>
                                </button>
                            </div>
                            <div class="flex items-center space-x-2">
                                <span class="text-sm text-gray-600">每页显示</span>
                                <select id="pageSizeSelect" class="border border-gray-300 rounded-lg px-3 py-1.5 focus:outline-none focus:ring-2 focus:ring-blue-500 focus:border-blue-500 bg-gray-50 text-sm">
                                    <option value="5">5条</option>
                                    <option value="10">10条</option>
                                    <option value="15">15条</option>
                                    <option value="20">20条</option>
                                </select>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>
</main>

<!-- Footer -->
<footer class="bg-gray-50 mt-12">
    <div class="container mx-auto px-4 py-8">
        <div class="grid grid-cols-1 md:grid-cols-4 gap-8">
            <div>
                <div class="flex items-center space-x-2 mb-4">
                    <i class="fas fa-plane text-2xl text-blue-500"></i>
                    <h3 class="text-xl font-bold logo-text">花龙腾航</h3>
                </div>
                <p class="text-gray-600 text-sm">花龙腾航，让您的每一次飞行都成为美好回忆。我们致力于提供安全、舒适、便捷的航空服务。</p>
            </div>
            <div>
                <h4 class="font-bold text-gray-800 mb-4">关于我们</h4>
                <ul class="space-y-2 text-sm text-gray-600">
                    <li><a href="public_company_profile" class="hover:text-blue-500 transition">公司简介</a></li>
                    <li><a href="public_company_profile" class="hover:text-blue-500 transition">企业文化</a></li>
                    <li><a href="public_company_profile" class="hover:text-blue-500 transition">发展历程</a></li>
                    <li><a href="public_job_posting" class="hover:text-blue-500 transition">招贤纳士</a></li>
                </ul>
            </div>
            <div>
                <h4 class="font-bold text-gray-800 mb-4">帮助中心</h4>
                <ul class="space-y-2 text-sm text-gray-600">
                    <li><a href="public_faq" class="hover:text-blue-500 transition">常见问题</a></li>
                    <li><a href="public_baggage_regulations" class="hover:text-blue-500 transition">行李规定</a></li>
                    <li><a href="public_company_profile" class="hover:text-blue-500 transition">航班动态</a></li>
                    <li><a href="public_callus" class="hover:text-blue-500 transition">联系客服</a></li>
                </ul>
            </div>
            <div>
                <h4 class="font-bold text-gray-800 mb-4">联系我们</h4>
                <ul class="space-y-2 text-sm text-gray-600">
                    <li class="flex items-center"><i class="fas fa-phone-alt mr-2 text-blue-500"></i> 客服热线: 19976338635</li>
                    <li class="flex items-center"><i class="fas fa-envelope mr-2 text-blue-500"></i> ganshenghao888@qq.com</li>
                    <li class="flex items-center"><i class="fas fa-map-marker-alt mr-2 text-blue-500"></i> 广东省广州市天河区华南农业大学</li>
                </ul>
                <div class="flex space-x-4 mt-4">
                    <a href="https://weixin.com" class="h-8 w-8 rounded-full bg-blue-100 flex items-center justify-center text-blue-500 hover:bg-blue-200 transition">
                        <i class="fab fa-weixin"></i>
                    </a>
                    <a href="https://weibo.com" class="h-8 w-8 rounded-full bg-blue-100 flex items-center justify-center text-blue-500 hover:bg-blue-200 transition">
                        <i class="fab fa-weibo"></i>
                    </a>
                    <a href="https://qq.com" class="h-8 w-8 rounded-full bg-blue-100 flex items-center justify-center text-blue-500 hover:bg-blue-200 transition">
                        <i class="fab fa-qq"></i>
                    </a>
                </div>
            </div>
        </div>
        <div class="border-t border-gray-200 mt-8 pt-6 text-center text-sm text-gray-500">
            <p>© 2025 花龙腾航航空公司 版权所有 | 京ICP备12345678号</p>
        </div>
    </div>
</footer>

<div class="fixed bottom-8 right-8 z-50">
    <button onclick="toggleChat()" class="bg-blue-500 text-white p-4 rounded-full shadow-lg hover:bg-blue-600">
        <i class="fas fa-comment-dots text-2xl"></i>
    </button>

    <div id="chat-window" class="hidden fixed bottom-24 right-8 w-96 bg-white rounded-lg shadow-xl">
        <div class="bg-blue-500 text-white p-4 rounded-t-lg flex justify-between">
            <h3 class="font-bold">智能客服</h3>
            <button onclick="toggleChat()" class="hover:text-blue-200">
                <i class="fas fa-times"></i>
            </button>
        </div>
        <div class="h-96 p-4 overflow-y-auto" id="chat-messages">
            <div class="text-gray-500 text-sm">您好！请问需要什么帮助？</div>
        </div>
        <form id="chat-form" onsubmit="sendMessage(this, event)" class="border-t p-4">
            <div class="flex gap-2">
                <label>
                    <input type="text" id="message-input" name="message"
                           class="flex-1 border rounded-lg p-2"
                           placeholder="输入问题..."
                           required
                           maxlength="200">
                </label>
                <button type="submit" class="bg-blue-500 text-white px-4 py-2 rounded-lg">
                    <i class="fas fa-paper-plane"></i>
                </button>
            </div>
        </form>
    </div>
</div>

<script>
    // Current page and page size
    let currentPage = 1;
    let pageSize = localStorage.getItem('pageSize') || 5;
    let currentFilter = 'all';

    // DOM elements
    const ticketList = document.getElementById('ticket-list');
    const emptyState = document.getElementById('empty-state');
    const searchInput = document.getElementById('searchInput');
    const dateFilter = document.getElementById('dateFilter');
    const statusFilter = document.getElementById('statusFilter');
    const prevPageBtn = document.getElementById('prevPage');
    const nextPageBtn = document.getElementById('nextPage');
    const pageNumbers = document.getElementById('pageNumbers');
    const startItem = document.getElementById('startItem');
    const endItem = document.getElementById('endItem');
    const totalItems = document.getElementById('totalItems');
    const pageSizeSelect = document.getElementById('pageSizeSelect');

    // Initialize page
    function init() {
        // Set the saved page size
        pageSizeSelect.value = pageSize;
        renderPagination();
        addEventListeners();
    }

    // Filter tickets by status
    function filterTickets(status) {
        currentFilter = status;

        // Update active tab
        document.querySelectorAll('[id^="tab-"]').forEach(tab => {
            tab.classList.remove('tab-active');
            tab.classList.add('text-gray-500');
        });
        const activeTab = document.getElementById(`tab-${status}`);
        activeTab.classList.add('tab-active');
        activeTab.classList.remove('text-gray-500');

        // Apply filters
        applyFilters();
    }

    // Apply all filters (status, search, date)
    function applyFilters() {
        const searchTerm = searchInput.value.toLowerCase();
        const selectedDate = dateFilter.value;
        const selectedStatus = statusFilter.value;

        // Get all ticket elements
        const allTickets = document.querySelectorAll('.ticket-card');

        let visibleCount = 0;

        allTickets.forEach(ticket => {
            // Skip the empty state and pagination elements
            if (ticket.id === 'empty-state' || ticket.classList.contains('p-6')) {
                return;
            }

            const ticketId = ticket.querySelector('.ticket-header div .text-sm').textContent.toLowerCase();
            const fromCity = ticket.querySelector('.text-center:first-child .text-xl').textContent.toLowerCase();
            const toCity = ticket.querySelector('.text-center:last-child .text-xl').textContent.toLowerCase();
            const ticketDate = ticket.querySelector('.ticket-header div .text-xs').textContent;
            const statusBadge = ticket.querySelector('.status-badge');
            const status = statusBadge.textContent;

            // Status filter
            const matchesStatus = currentFilter === 'all' ||
                (currentFilter === 'upcoming' && status === '已出票') ||
                (currentFilter === 'scheduled' && status === '计划中') ||
                (currentFilter === 'completed' && status === '已完成') ||
                (currentFilter === 'cancelled' && status === '已取消') ||
                (currentFilter === 'delay' && status === '已延误');

            // Additional status filter from dropdown
            const matchesAdditionalStatus = selectedStatus === '' ||
                (selectedStatus === 'upcoming' && status === '已出票') ||
                (selectedStatus === 'scheduled' && status === '计划中') ||
                (selectedStatus === 'completed' && status === '已完成') ||
                (selectedStatus === 'cancelled' && status === '已取消') ||
                (selectedStatus === 'delay' && status === '已延误');

            // Search term - matches ticket ID, departure or arrival city
            const matchesSearch = searchTerm === '' ||
                ticketId.includes(searchTerm) ||
                fromCity.includes(searchTerm) ||
                toCity.includes(searchTerm);

            // Date filter
            const formattedTicketDate = ticketDate.replace(/(\d{4})-(\d{2})-(\d{2})/, '$1年$2月$3日');
            const matchesDate = selectedDate === '' ||
                formattedTicketDate.includes(selectedDate.split('-')[0] + '年' +
                    selectedDate.split('-')[1] + '月' +
                    selectedDate.split('-')[2] + '日');

            if (matchesStatus && matchesAdditionalStatus && matchesSearch && matchesDate) {
                ticket.style.display = '';
                visibleCount++;
            } else {
                ticket.style.display = 'none';
            }
        });

        // Show empty state if no tickets match
        if (visibleCount === 0) {
            emptyState.classList.remove('hidden');
        } else {
            emptyState.classList.add('hidden');
        }

        currentPage = 1;
        renderPagination();
    }

    // Change page size
    function changePageSize(newSize) {
        pageSize = parseInt(newSize);
        // Save to localStorage
        localStorage.setItem('pageSize', pageSize);
        currentPage = 1;
        renderPagination();
    }

    // Toggle ticket details
    function toggleTicketDetail(button) {
        const ticketDetail = button.closest('.ticket-card').querySelector('.ticket-detail');
        const icon = button.querySelector('i');

        ticketDetail.classList.toggle('open');

        if (ticketDetail.classList.contains('open')) {
            icon.classList.remove('fa-chevron-down');
            icon.classList.add('fa-chevron-up');
        } else {
            icon.classList.remove('fa-chevron-up');
            icon.classList.add('fa-chevron-down');
        }
    }

    // Pay ticket (simulated)
    function payTicket(ticketId) {
        // In a real application, this would make an AJAX call to the backend
        if (confirm(`确定要支付机票 ${ticketId} 吗？`)) {
            alert(`机票 ${ticketId} 支付成功！`);
            // Reload the page to reflect changes
            window.location.reload();
        }
    }

    // 设置票据信息和操作类型
    function handleTicketAction(button, actionType) {
        const ticketId = button.getAttribute('data-ticket-id');
        const flightId = button.getAttribute('data-flight-id');

        const actionMap = {
            cancel: "取消",
            pay: "支付",
            checkIn: "办理值机",
            reschedule: "改签",
            refund: "退票",
            rebook: "再次预定",
            issueInvoice: "开具发票"
        };

        const actionName = actionMap[actionType] || "执行此操作";

        if (confirm(`确定要${actionName}吗？`)) {
            // 设置隐藏字段并提交表单
            document.getElementById('ticketIdInput').value = ticketId;
            document.getElementById('flightIdInput').value = flightId;
            document.getElementById('actionTypeInput').value = actionType;

            document.getElementById('ticketForm').submit();
        } else {
            return false;
        }
    }

    // Render pagination controls
    function renderPagination() {
        const allTickets = document.querySelectorAll('.ticket-card');
        const visibleTickets = Array.from(allTickets).filter(ticket =>
            ticket.style.display !== 'none' &&
            ticket.id !== 'empty-state' &&
            !ticket.classList.contains('p-6')
        );
        const totalPages = Math.ceil(visibleTickets.length / pageSize);

        // Update prev/next buttons
        prevPageBtn.disabled = currentPage === 1;
        nextPageBtn.disabled = currentPage === totalPages || totalPages === 0;

        // Clear page numbers
        pageNumbers.innerHTML = '';

        // Calculate range of pages to show
        let startPage = Math.max(1, currentPage - 2);
        let endPage = Math.min(totalPages, currentPage + 2);

        // Ensure we show 5 pages if possible
        if (endPage - startPage < 4) {
            if (currentPage < totalPages / 2) {
                endPage = Math.min(startPage + 4, totalPages);
            } else {
                startPage = Math.max(endPage - 4, 1);
            }
        }

        // Add first page button
        if (startPage > 1) {
            addPageButton(1);
            if (startPage > 2) {
                const ellipsis = document.createElement('span');
                ellipsis.className = 'px-3 py-1';
                ellipsis.textContent = '...';
                pageNumbers.appendChild(ellipsis);
            }
        }

        // Add page buttons
        for (let i = startPage; i <= endPage; i++) {
            addPageButton(i);
        }

        // Add last page button
        if (endPage < totalPages) {
            if (endPage < totalPages - 1) {
                const ellipsis = document.createElement('span');
                ellipsis.className = 'px-3 py-1';
                ellipsis.textContent = '...';
                pageNumbers.appendChild(ellipsis);
            }
            addPageButton(totalPages);
        }

        // Update pagination info
        const startIndex = (currentPage - 1) * pageSize;
        const endIndex = Math.min(startIndex + pageSize, visibleTickets.length);

        startItem.textContent = startIndex + 1;
        endItem.textContent = endIndex;
        totalItems.textContent = visibleTickets.length;

        // Show/hide tickets based on current page
        visibleTickets.forEach((ticket, index) => {
            if (index >= startIndex && index < endIndex) {
                ticket.style.display = '';
            } else {
                ticket.style.display = 'none';
            }
        });
    }

    // Add a page button
    function addPageButton(page) {
        const button = document.createElement('button');
        button.className = `px-3 py-1 rounded-lg text-sm font-medium ${currentPage === page ? 'bg-blue-600 text-white' : 'bg-white text-gray-700 hover:bg-gray-50'}`;
        button.textContent = page;
        button.addEventListener('click', () => {
            currentPage = page;
            renderPagination();
            window.scrollTo({ top: 0, behavior: 'smooth' });
        });
        pageNumbers.appendChild(button);
    }

    // Add event listeners
    function addEventListeners() {
        // Search input
        searchInput.addEventListener('input', () => {
            applyFilters();
        });

        // Date filter
        dateFilter.addEventListener('change', () => {
            applyFilters();
        });

        // Status filter
        statusFilter.addEventListener('change', () => {
            applyFilters();
        });

        // Previous page
        prevPageBtn.addEventListener('click', () => {
            if (currentPage > 1) {
                currentPage--;
                renderPagination();
                window.scrollTo({ top: 0, behavior: 'smooth' });
            }
        });

        // Next page
        nextPageBtn.addEventListener('click', () => {
            const allTickets = document.querySelectorAll('.ticket-card');
            const visibleTickets = Array.from(allTickets).filter(ticket =>
                ticket.style.display !== 'none' &&
                ticket.id !== 'empty-state' &&
                !ticket.classList.contains('p-6')
            );
            const totalPages = Math.ceil(visibleTickets.length / pageSize);

            if (currentPage < totalPages) {
                currentPage++;
                renderPagination();
                window.scrollTo({ top: 0, behavior: 'smooth' });
            }
        });

        // Page size selector
        pageSizeSelect.addEventListener('change', (e) => {
            changePageSize(e.target.value);
        });
    }

    // Initialize the page
    document.addEventListener('DOMContentLoaded', init);
</script>
<script>
    document.addEventListener('DOMContentLoaded', function() {
        // 用户菜单功能
        const userMenu = document.getElementById('user-menu');
        const dropdownMenu = document.getElementById('dropdown-menu');

        userMenu.addEventListener('click', (event) => {
            event.stopPropagation();
            dropdownMenu.classList.toggle('open');
        });

        document.addEventListener('click', (event) => {
            const isClickInside = userMenu.contains(event.target) || dropdownMenu.contains(event.target);
            if (!isClickInside) {
                dropdownMenu.classList.remove('open');
            }
        });

        // 聊天功能
        const chatWindow = document.getElementById('chat-window');
        const chatForm = document.getElementById('chat-form');
        let isSending = false;

        window.toggleChat = function() {
            chatWindow.classList.toggle('hidden');
            if (!chatWindow.classList.contains('hidden')) {
                document.getElementById('chat-messages').scrollTop = document.getElementById('chat-messages').scrollHeight;
            }
        };

        window.sendMessage = async function(form, event) {
            event.preventDefault();

            if (isSending) return false;
            isSending = true;

            const input = document.getElementById('message-input');
            const message = input.value.trim();

            console.log('发送的消息:', message);

            if (!message) {
                alert("请输入有效内容");
                isSending = false;
                return false;
            }

            try {
                addMessage('user', message);
                input.value = '';
                const loader = addMessage('assistant', '<div class="dot-pulse"></div>');

                const contextPath = window.location.pathname.split('/')[1];
                const response = await fetch(`/${contextPath}/ChatServlet`, {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8'
                    },
                    body: `message=${encodeURIComponent(message)}`
                });

                if (!response.ok) {
                    throw new Error(`HTTP错误! 状态码: ${response.status}`);
                }

                const data = await response.text();
                loader.remove();
                addMessage('assistant', data);
            } catch (error) {
                console.error('请求失败:', error);
                addMessage('assistant', `服务暂时不可用（${error.message}）`);
                alert(`请求失败: ${error.message}`);
            } finally {
                isSending = false;
            }
            return false;
        };

        function addMessage(role, content) {
            console.log("添加消息 - 角色:", role, "内容:", content);
            const container = document.getElementById('chat-messages');
            const div = document.createElement('div');
            div.className = `mb-4 flex ${role === 'user' ? 'justify-end' : 'justify-start'}`;

            const contentDiv = document.createElement('div');
            contentDiv.className = role === 'user'
                ? 'bg-blue-500 text-white rounded-lg p-3 max-w-[80%]'
                : 'bg-gray-100 text-gray-800 rounded-lg p-3 max-w-[80%]';

            contentDiv.innerHTML = content;
            div.appendChild(contentDiv);
            container.appendChild(div);

            container.scrollTo({
                top: container.scrollHeight,
                behavior: 'smooth'
            });

            return div;
        };

        document.getElementById('message-input').addEventListener('keypress', (e) => {
            if (e.key === 'Enter' && !e.shiftKey) {
                e.preventDefault();
                chatForm.requestSubmit();
            }
        });
    });
</script>
</body>
</html>